//License: Artistic License v2.0, http://opensource.org/licenses/Artistic-2.0

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

func readDataFiles() (err error) {
	log.Println(projName, "Reading config")
	err = readConfigFile(path("configFile"))
	if err != nil {
		log.Println(projName, err)
		return err
	}
	log.Println(projName, "Reading MobileRegexp")
	err = SetMobileDetection(path("mobileRegexpFile"))
	if err != nil {
		log.Println(projName, err)
		return err
	}
	if conf.TrackLocation {
		log.Println(projName, "Reading IPLocationTable")
		err = SetIPLocationTable(conf.IPTableFile, conf.IPToColumn)
		if err != nil {
			log.Println(projName, err)
			return err
		}
	}
	log.Println(projName, "Reading layout snippets for theme")
	err = readSnippetFiles() //sets global: snippets, supportedLang
	if err != nil {
		log.Println(projName, err)
		return err
	}
	log.Println(projName, "Reading copies")
	copies, err = readCopyFiles()
	if err != nil {
		log.Println(projName, err)
		return err
	}
	writeSiteMap(conf.Domain, path("static"))
	return err
}

func readConfigFile(fname string) (err error) {
	tconfig := conf
	err = Json("get", fname, &tconfig)
	if err != nil {
		log.Println(projName, err)
		return err
	}
	conf = tconfig
	return nil
}

func readSnippetFiles() error {
	//folder struct: folderName/lang/tid
	f1, e1 := os.Open(path("snippet"))
	defer f1.Close()
	if e1 != nil {
		return e1
	}
	langs, e2 := f1.Readdirnames(-1)
	if e2 != nil {
		return e2
	}
	for _, lang := range langs {
		supportedLang[lang] = true
		f2, e3 := os.Open(path("snippet") + lang)
		defer f2.Close()
		if e3 != nil {
			return e3
		}
		snippetNames, e4 := f2.Readdirnames(-1)
		if e4 != nil {
			return e4
		}
		if snippets[lang] == nil {
			snippets[lang] = map[string]string{}
		}
		for _, fname := range snippetNames {
			snippetStr, e5 := ioutil.ReadFile(path("snippet") + lang + sep + fname)
			if e5 != nil {
				return e5
			}
			snippets[lang][fname] = string(snippetStr)
		}
	}
	return nil
}

func readCopyFiles() (map[string]Copy, error) {
	var tcopies = map[string]Copy{}
	f, err := os.Open(path("meta"))
	defer f.Close()
	if err != nil {
		return tcopies, err
	}
	fnames, err := f.Readdirnames(-1)
	if err != nil {
		return tcopies, err
	}
	for _, fname := range fnames {
		if strings.HasSuffix(fname, ".json") {
			c := new(Copy)
			err = Json("get", path("meta")+fname, &c)
			if err != nil {
				return tcopies, err
			}
			tcopies[c.Cid] = *c
		}
	}
	for cid := range tcopies {
		buf, err := ioutil.ReadFile(path("copy") + cid + ".html")
		if err != nil {
			buf, err = ReadFileMarkdownToHTML(path("copy") + cid + ".md")
			if err != nil {
				return tcopies, err
			}
		}
		c := tcopies[cid] //compiler disliked tcopies [cid].Copy = string (buf)
		c.Copy = string(buf)
		tcopies[cid] = c
	}
	writeSiteMap(conf.Domain, path("static"))
	return tcopies, nil
}

func newLog(folderPath, fileName, fileType string) os.File {
	var fname string = fmt.Sprintf("%s%s%s.%s",
		folderPath, fileName, strconv.FormatInt(time.Now().Unix(), 10), fileType)
	f, err := os.OpenFile(fname, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
	if err != nil {
		log.Println(projName, err)
	}
	return *f
}

func path(name string) string {
	var goblWD string = os.Getenv("GOBLWD")
	if goblWD == "" {
		goblWD = "./"
	} else if goblWD[len(goblWD)-1] != os.PathSeparator { //goblWD needs to end with sep
		goblWD = goblWD + sep
	}
	//Not the most elegant code, but the easiest to follow IMHO
	switch name {
	case "readmeFile":
		return goblWD + "readme.txt"
	case "exampleFile":
		return goblWD + "example.txt"
	case "user":
		return goblWD + "user" + sep
	case "log":
		return goblWD + "log" + sep
	case "connectionConfigFile":
		return goblWD + "log" + sep + "connectionConfig.json"
	case "seed":
		return goblWD + "seed" + sep
	case "seedProj":
		return goblWD + "seed" + sep + "proj" + sep
	case "seedTheme":
		return goblWD + "seed" + sep + "theme" + sep
	case "proj":
		return goblWD + "proj" + sep + projName + sep
	case "config":
		return goblWD + "proj" + sep + projName + sep + "config" + sep
	case "configFile":
		return goblWD + "proj" + sep + projName + sep + "config" + sep + "config.json"
	case "mobileRegexpFile":
		return goblWD + "proj" + sep + projName + sep + "config" + sep + "mobileRegexp.txt"
	case "data":
		return goblWD + "proj" + sep + projName + sep + "data" + sep
	case "copy":
		return goblWD + "proj" + sep + projName + sep + "data" + sep + "copy" + sep
	case "meta":
		return goblWD + "proj" + sep + projName + sep + "data" + sep + "meta" + sep
	case "static":
		return goblWD + "proj" + sep + projName + sep + "data" + sep + "static" + sep
	case "themeDir":
		return goblWD + "proj" + sep + projName + sep + "theme" + sep
	case "theme":
		return goblWD + "proj" + sep + projName + sep + "theme" + sep + conf.Theme + sep + "static" + sep
	case "snippet":
		return goblWD + "proj" + sep + projName + sep + "theme" + sep + conf.Theme + sep + "snippet" + sep
	}
	log.Println(projName, "Err: dataRW path() NOT found - ", name)
	return ""
}

//Copyright: Slamet Hendry
